package com.cyh;

import java.util.LinkedList;

//消息队列
public class MessageQueue {
    //消息集合
    private LinkedList<Message> list = new LinkedList<>();
    //消息容量
    private int capcity;

    public MessageQueue(int capcity) {
        this.capcity = capcity;
    }

    //获取消息
    public Message take() {
        synchronized (list) {
            while(list.isEmpty()) {
                try {
                    System.out.println("队列为空， 消费者等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            Message msg = list.removeFirst();
            System.out.println("已消费消息--" + msg);
            list.notifyAll();
            return msg;
        }
    }

    //存入消息
    public void put(Message message) {
        synchronized (list) {
            while(list.size() == capcity) {
                try {
                    System.out.println("---队列为满， 生产者等待");
                    list.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            list.add(message);
            System.out.println("已生产消息-----" + message);
            list.notifyAll();
        }
    }
}
